class MyPromise {
  static PENDING = "待定";
  static FULFILLED = "成功";
  static REJECT = "拒绝";
  constructor(fun) {
    this.status = MyPromise.PENDING;
    this.result = null;
    this.resArr = [];
    this.rejArr = [];
    fun(this.resolve.bind(this), this.reject.bind(this));
  }
  resolve(result) {
    if (this.status === MyPromise.PENDING) {
      this.status = MyPromise.FULFILLED;
      this.result = result;
      this.rejArr.forEach((fun) => fun(result));
    }
  }
  reject(result) {
    if (this.status === MyPromise.PENDING) {
      this.status = MyPromise.REJECT;
      this.result = result;
      this.resArr.forEach((fun) => fun(result));
    }
  }
  then(fulFun, rejFun) {
    // 原生的promise的then方法返回的还是promise
    return new MyPromise((resolve, reject) => {
      // 如果传入的不是函数或者没有传值
      fulFun = typeof fulFun === "function" ? fulFun : () => {};
      rejFun = typeof rejFun === "function" ? rejFun : () => {};

      if (this.status === MyPromise.FULFILLED) {
        // 模拟异步
        setTimeout(() => {
          console.log("ful");
          fulFun(this.result);
        });
      } else if (this.status === MyPromise.REJECT) {
        // 模拟异步
        setTimeout(() => {
          console.log("rej");
          rejFun(this.result);
        });
      } else {
        // 如果状态还是pending则放入队列
        this.resArr.push(fulFun);
        this.rejArr.push(rejFun);
      }
    });
  }
}

console.log(1);
const p = new MyPromise((resolve, reject) => {
  console.log(2);
  setTimeout(() => {
    // resolve("啦啦啦1");
    reject("啦啦啦2");
  });
  console.log(3);
});
p.then(
  (res) => {
    console.log(res);
  },
  (err) => {
    console.log(err);
  }
);
console.log(4);
